# coding:utf-8
class TerminalOrder < ActiveRecord::Base
  has_paper_trail :version => :paper_trail_version, :versions => :paper_trail_versions
  extend OpenSpreadsheet
  ORDER_NAMES = {
    'yidong' => '移动版',
    'zengqiang' => '加强版'
  }

  belongs_to :terminal_user
  belongs_to :terminal
  belongs_to :terminal_group

  accepts_nested_attributes_for :terminal_user, :terminal

  validates :worker, :presence => true
  validates :name, inclusion: { in: self::ORDER_NAMES.keys }

  validates_presence_of :setup_at,:worker


  # scope :by_mac, lambda {|mac| joins(:terminal).where(["terminals.mac like ?", '%'+mac+'%'])}
  # scope :by_address, lambda {|address| joins(:terminal_user).where(["terminal_users.address like ? or terminal_users.car_license like ?", '%'+address+'%', '%'+address+'%'])}
  # scope :by_worker, lambda {|worker| where(["worker like ?", '%'+worker+'%'])}
  # scope :before_date, lambda {|date| where(["created_at < ?", 1.days.since(Time.zone.parse(date)).strftime("%Y-%m-%d")])}
  # scope :after_date, lambda {|date| where(["created_at >= ?", date])}

  def display_name
    'Y-BOX' + TerminalOrder::ORDER_NAMES[self.name].to_s
  end

  def display_in_tree
    "#{self.display_name} #{self.terminal.mac} #{self.terminal_user.name}"
  end

  def self.to_csv(options = {})
    CSV.generate(options) do |csv|
      csv << ["\xEF\xBB\xBF类型", "安装日期", "mac地址","3G网卡型号","IMEI",'资费卡ICCID','联系人','用户单位','联系电话','行业类型','地址(加强版)','车牌号(移动版)','司机姓名','司机联系电话','司机姓名2','司机联系电话2','车辆所属单位','11位用户号码','工单负责人','工单负责人电话']
    end
  end

  def terminal_order_csv_attrs
    [TerminalOrder::ORDER_NAMES[self.name],
      self.setup_at,
      self.terminal.mac.split(':').join,
      self.terminal.networkcard3g_model,
      self.terminal.imei,
      self.terminal.sim_iccid,
      self.terminal_user.name,
      self.terminal_user.user_unit,
      self.terminal_user.phone,
      self.terminal_user.industry,            
      self.terminal_user.address,
      self.terminal_user.car_license,
      self.terminal_user.driver_name,
      self.terminal_user.driver_phone,
      self.terminal_user.driver_name2,
      self.terminal_user.driver_phone2,
      self.terminal_user.car_unit,
      self.terminal_user.user_number,
      self.worker,
      self.worker_phone].join("\t")
  end

  def self.import(file,terminal_group_id)
    begin
      Terminal.transaction do
        file = open_spreadsheet(file)
        CSV.foreach(file.path, headers: true) do |row|
          row.to_hash.each do |key,value|
            terminal_order = TerminalOrder.new(:terminal_group_id => terminal_group_id)
            terminal_order.build_terminal(:terminal_group_id => terminal_group_id)
            terminal_order.build_terminal_user
            value.split("\t").each_with_index do |attr_value,index|
              case index
              when 0
                terminal_order.name = TerminalOrder::ORDER_NAMES.invert[attr_value] if TerminalOrder::ORDER_NAMES.value?(attr_value)
              when 1
                terminal_order.setup_at = attr_value.to_date if Date.parse('xx')
              when 2
                terminal_order.terminal.mac = attr_value
              when 3
                terminal_order.terminal.networkcard3g_model = attr_value
              when 4
                terminal_order.terminal.imei = attr_value
              when 5
                terminal_order.terminal.sim_iccid = attr_value
              when 6
                terminal_order.terminal_user.name = attr_value
              when 7
                terminal_order.terminal_user.user_unit = attr_value
              when 8
                terminal_order.terminal_user.phone = attr_value
              when 9
                terminal_order.terminal_user.industry = attr_value            
              when 10
                terminal_order.terminal_user.address = attr_value
              when 11
                terminal_order.terminal_user.car_license = attr_value
              when 12
                terminal_order.terminal_user.driver_name = attr_value
              when 13
                terminal_order.terminal_user.driver_phone = attr_value
              when 14
                terminal_order.terminal_user.driver_name2 = attr_value
              when 15
                terminal_order.terminal_user.driver_phone2 = attr_value
              when 16
                terminal_order.terminal_user.car_unit = attr_value
              when 17
                terminal_order.terminal_user.user_number = attr_value
              when 18
                terminal_order.worker = attr_value
              when 19
                terminal_order.worker_phone = attr_value.to_s
              end
            end

            terminal_order.save!
          end
        end
        #TerminalGroup.reset_counters terminal_group_id, :terminals
      end
      true
    rescue => e 
      raise e
    end
  end

end
